package com.scientific.research.gobang.utils;

import java.io.*;

public class FileUtils {

    //获取操作系统类型
    public static String getOs() {
        String result = System.getProperty("os.name");
        if (result.contains("Windows")) {
            return "windows";
        } else {
            return "linux";
        }
    }

    //获取用户目录
    public static String getBasePath() {
        return System.getProperty("user.home");
    }

    //读取一个文件
    public static String read(String path) {
        StringBuilder result = new StringBuilder();
        String between;
        try {
            FileReader read = new FileReader(path);
            BufferedReader reader = new BufferedReader(read);
            while ((between = reader.readLine()) != null) {
                result.append(between).append("\n");
            }
            read.close();
            reader.close();
        } catch (IOException e) {
            System.out.println("读取文件 " + path + " 错误！");
            e.printStackTrace();
        }
        return result.toString();
    }

    //写入文件操作，bool值用于追加代码与否
    public static void writer(String path, String value, boolean append) {
        try {
            FileWriter w = new FileWriter(path, append);
            BufferedWriter writ = new BufferedWriter(w);
            writ.write(value);
            writ.flush();
            writ.close();
            w.close();
        } catch (IOException e) {
            System.out.println("写入文件 " + path + " 失败！");
            e.printStackTrace();
        }
    }

    //删除单个文件
    public static void deleteFile(File file) {
        if (file.exists()) {
            if (!file.delete()) {
                System.out.println("错误：文件 " + file.getAbsolutePath() + " 删除失败！");
            }
        }
    }

    //删除整个目录
    public static void deleteDirectory(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) {
                deleteFile(file);
            } else {
                for (File f : files) {
                    deleteDirectory(f);
                }
                deleteFile(file);
            }
        } else {
            deleteFile(file);
        }
    }
}
